<template>
    <el-form :model="peradd" label-width="auto" style="max-width: 600px;margin-left: 200px;">
        <div>
            <H1 style="margin-left: 200px;">添加角色</H1>
        </div>
        <el-form-item label="角色名称:">
            <el-input v-model="peradd.roleName" />
        </el-form-item>
        <el-form-item label="权限:">
            <el-checkbox-group v-model="peradd.permissionId">
                <el-checkbox v-for="a in perselect" :value="a.permissionId" name="type">
                    {{ a.permissionName }}
                </el-checkbox>
            </el-checkbox-group>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button @click="bient">返回</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { Read, Write } from '@/Http/axios'
import { ElMessage } from "element-plus";
import { useCounterStore } from '@/stores/counter';
import router from '@/router'
import { useRoute } from 'vue-router'
const store = useCounterStore();
const route = useRoute()

const peradd = reactive({
    "roleName": "",
    "states": true,
    "createdTime": "2025-09-15T07:06:03.027Z",
    "roleId": route.query.roleId,
    "permissionId": [
        0
    ]
})
//用户添加方法
const onSubmit = () => {
    Write.post("/Management/RoleUpdate", peradd).then(res => {
        if (res.data.code == 400) {
            ElMessage.success("修改成功")
            router.push('/RoleShow')
        }
        else {
            ElMessage.error("修改失败")
        }
    }).catch(err => {
        console.log(err)
    })
}

//权限复选框
const perselect = <any>ref([])

const perselectlist = () => {
    Read.get("/Management/PerSelect").then(res => {
        perselect.value = res.data.data
    }).catch(err => {
        console.log(err)
    })
}

//角色反填方法
const rolebacefile = () => {
    let roleId = route.query.roleId;
    Read.get("/Management/RoleBackFileGet", {
        params: {
            RoleId: roleId
        }
    }).then(res => {
        console.log(res.data);
        peradd.roleName = res.data.data[0].roleName
        // 确保权限ID是数组格式
        const permissionIds = res.data.data[0].permissionId
        peradd.permissionId = Array.isArray(permissionIds) ? permissionIds : [permissionIds]

    })
}



//钩子函数
onMounted(() => {
    perselectlist();
    rolebacefile();
})
//返回
const bient = () => {
    router.push('/RoleShow')
}


</script>
